<template>
  <div class="container">
    <div class="login-box">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="70px" :inline="true">
        <h3 class="login_title">系统登录</h3>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" @blur="validateField('username')"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" @blur="validateField('password')"></el-input>
        </el-form-item>
        <el-radio-group v-model="loginRole" class="roleSetting">
          <el-radio :label="0">用户</el-radio>
          <el-radio :label="1">管理员</el-radio>
        </el-radio-group>
      </el-form>
      <div class="buttonSubmit">
        <el-button type="primary" class="login_button" @click="gotoLogin">登录</el-button>
        <el-button type="success" @click="gotoRegister">去注册</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import router from "../router";
import UserApi from "../apis/api.js";
import { ElMessage } from 'element-plus';
import TokenStorage from "@/utils/token";


const form = reactive({
  username: '',
  password: '',
});

const rules = {
  username: [
    { required: true, trigger: 'blur', message: '请输入用户名' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入密码' }
  ]
};

// 设置默认选择用户
const loginRole = ref(0);

const formRef = ref(null);

const validateField = (field) => {
  formRef.value.validateField(field);
};

// 跳转注册页面
const gotoRegister = () => {
  router.push({ path: '/Register' });
}

// 定义登录方法
const gotoLogin = () => {
  const { username, password } = form;
  const role = loginRole.value;
  const user = { username, password, isUser: role };

  UserApi.LoginUser(user).then((res) => {
    console.log(res);
    const flag = res.code;
    if (flag !== 200) {
      ElMessage.error({
        message: res.data,
        duration: 1500,
      });
      form.username = '';
      form.password = '';
    } else if (flag === 200) {
      localStorage.setItem('jwtToken', res.data);
      const userRole = TokenStorage.get().role;
      console.log(userRole);
      ElMessage.success({
        message: '登录成功',
        duration: 1500,
      });
      if (userRole === 'user') {
        router.push({ path: "/user/home" });
      } else if (userRole === 'admin') {
        router.push({ path: "/admin/dashboard" });
      } else {
        ElMessage.error({
          message: '未知角色',
          duration: 1500,
        });
        router.push({ path: "/login" });
      }
    }
  }).catch((error) => {
    console.error('登录失败:', error);
    ElMessage.error({
      message: '登录失败，请重试',
      duration: 1500,
    });
  });
}
</script>

<style scoped>
.container {
  background-image: url("../img/Login.jpg");
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  height: 100vh;
}
.login-box {
  width: 300px;
  height: 250px;
  padding: 20px;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
.login_title {
  text-align: center;
  margin-bottom: 40px;
  color: #505458;
}
.roleSetting {
  margin-left: 80px;
}
.buttonSubmit {
  margin-left: 80px;
}
.login_button {
  margin-right: 20px;
}
</style>
